<?php
namespace Admin\Frontend\Controllers;

use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\sys\XhsysGrade;
use Helpers\User;
use Admin\Models\school\XhschoolWeekly;
use Admin\Models\track\XhtrackTask;
use Admin\Models\track\XhtrackTch;
use Admin\Models\user\XhsysUser;
use Modules\Msg;
use Modules\Power;
use Modules\School;
use Phalcon\Mvc\View;
use Helpers\Tool;
use Helpers\Main;
use Helpers\Cache;
use Helpers\Assets;
use Helpers\Template;
use Helpers\EnumList;
use Helpers\HttpClient;
use Helpers\UserPower;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\school\XhschoolAppgroup;
use Admin\Models\school\XhschoolAppgroupapp;
use Admin\Models\school\XhschoolUserappgroup;
use Admin\Models\school\XhschoolAppstore;
use Admin\Models\device\XhsysUsertablet;
use Admin\Models\device\XhsysAccountdevicelocked;


class SchoolWeekController extends ControllerBase
{

    private $taskType    = [1 => '需求', 2 => 'BUG', 3 => '资源'];

    private $weekState   = [0 => '新建',1 => '待审核', 2 => '通过' , 3 => '退回' ];

    /**
     * 获取日期   上周日~这周六 
     *
     * @return array
     *
     * created by dale 20171118
     * modify by dale 20180509  用于周报的默认时间
     */
    public function getWeekAction(){
        $nowDate = date('Y-m-d',time());
        $w = date('w',strtotime($nowDate));
        $m = date('m',strtotime($nowDate));
        $d = date('d',strtotime($nowDate));
        $Y = date('Y',strtotime($nowDate));
        $startDay = date("Y-m-d H:i:s", mktime(0, 0, 0, $m, $d - $w - 7, $Y));
        $endDay = date("Y-m-d H:i:s", mktime(0, 0, 0, $m, $d - $w - 1 , $Y));
        return ['startDay'=>$startDay,'endDay'=>$endDay];
    }

    /**
     * ajax获取到日期拼接成时间戳
     *
     * @param $startDay
     * @param $endDay
     *
     * create by xjq 20180509
     */
    public function getFixDate($startDay, $endDay)
    {
        return ['startDay' => $startDay.' 00:00:00', 'endDay' => $endDay.' 23:59:59'];
    }


    /**
     * 学校周报界面  视图
     *
     * created by dale 20171118
     */
    public function weeklyAction()
    {
//         $this->view->disable();
        UserPower::checkUserPower('School_List_Weekly') or die('缺少权限');
        $schoolId = $this->request->getQuery('schoolId');
        $iSWId    = $this->request->getQuery('iSWId');
        $iUserId  = Main::getLoginUserInfo('userId');
        $day      =  $this->getWeekAction();
        $startDay = $day['startDay'];
        $endDay   = $day['endDay'];
//        $endDay = date("Y-m-d H:i:s", mktime(23, 59, 59, date("m"), date("d") - date("w") + 7, date("Y")));
        $this->view->pick('school_week/weekly');
        Assets::viewer();
        $this->di->get('assets')
            ->addCss('assets/fileinput/fileinput.css')
            ->addJs('customer/js/fileinput.min.js')//修改过的
            ->addJs('customer/js/zh.js');
        Assets::easyUI('../customer/js/myMain.js');
        Assets::importJs('js/school_week/weekly.js');
        if($iSWId){
            $obj = XhschoolWeekly::findFirst([
                'conditions'=>'iSWId = :iSWId:',
                'bind'      =>['iSWId'=>$iSWId],
            ]);
        }
        if($obj){
            $data  = $obj->toArray();
            $schoolId = $data['iSchoolId'];
            $data['mAppAnalyze'] = gzuncompress( base64_decode($data['mAppAnalyze']));
            $data['mTchTrack']   = gzuncompress( base64_decode($data['mTchTrack']));
            $data['mTaskTrack']  = gzuncompress( base64_decode($data['mTaskTrack']));
            $data['mPClass']     = gzuncompress( base64_decode($data['mPClass']));
            $data['startDay']    = date('Y-m-d',$data['iStartDay']);
            $data['endDay']      = date('Y-m-d',$data['iEndDay']);
            $info = json_encode($data);
        }else{
            $info = '1';
        }
        $chekPower = false;
        if($obj && UserPower::checkUserPower('School_List_Weekly_Check')){
            if(Main::getLoginUserInfo('logonName')=='admin'){
                $chekPower = true;
            }else{
                $changeArr = $this->getChargeById($obj->iCreateUserId , true);//所有的负责人数组
                if (in_array(Main::getLoginUserInfo('userId') , $changeArr)) {
                    $chekPower = true;
                }
//                $creater = XhhrmStaff::findFirst([
//                    'columns'    => 'sDepIds',
//                    'conditions' => 'iUserId = :iUserId: AND bDelete=0',
//                    'bind'       => ['iUserId'=>$obj->iCreateUserId],
//                ]);
//                if($creater){ //创建者存在
//                    $deps = array_values(array_filter(explode(',',$creater->sDepIds)));
//                    if(isset($deps[0])){
//                        $staff = XhhrmStaff::findFirst([
//                            'columns'    => 'sChargeDeps',
//                            'conditions' => 'iUserId = :iUserId:',
//                            'bind'       => ['iUserId'=>$iUserId],
//                        ]);
//                        if($staff && $staff->sChargeDeps != null ){
//                            $sChargeDeps = array_values(explode(',',$staff->sChargeDeps));
//                            foreach ($sChargeDeps as $val){
//                                if($val == $deps[0] ){
//                                    $chekPower = true;
//                                }
//                            }
//                        }
//                    }
//                }

            }
        }

        if($chekPower){ //审核
            $passStr = '<div class="ddv" style="position:fixed;background-color: #ececec;border-top:1px solid #ccc;width:100%;height:50px;bottom:0;left:0;display: none"><a id="pass" class="btn  btn-success pull-right xh-btn-load" style="margin-right: 20px;">通过</a><a  id="back" class="btn btn-default pull-right xh-btn-load" style="margin-right: 5px;">退回</a></div>';
        }else{
            $passStr = '';
        }
        if(UserPower::checkUserPower('School_List_Weekly_Add')){ //新增
            if($obj && $obj->iCreateUserId != $iUserId){  //如果创建的Id==用户id
                $addStr = '';
            }else{
                $addStr = '<div class="ddv" style="position:fixed;background-color: #ececec;border-top:1px solid #ccc;width:100%;height:50px;bottom:0;left:0;"><a  id="submit" class="btn btn-success pull-right xh-btn-load" style="margin-right: 20px;">提交</a><a id="save" class="btn  btn-primary pull-right xh-btn-load" style="margin-right: 5px;">保存</a></div>';
            }
            if(Main::getLoginUserInfo('logonName')=='admin'){ //如果超管
                $addStr = '<div class="ddv" style="position:fixed;background-color: #ececec;border-top:1px solid #ccc;width:100%;height:50px;bottom:0;left:0;"><a  id="submit" class="btn btn-success pull-right xh-btn-load" style="margin-right: 20px;">提交</a><a id="save" class="btn  btn-primary pull-right xh-btn-load" style="margin-right: 5px;">保存</a></div>';
            }

        }else{
            $addStr = '';
        }
        $this->view->setVars([
            'info'    => $info,
            'passStr' =>$passStr,
            'addStr'  =>$addStr,
            'iSchoolId'=>$schoolId,
            'iStartDay'=>date('Y-m-d' , strtotime($startDay)),
            'iEndDay'=>date('Y-m-d' , strtotime($endDay) )
        ]);
    }

    /*
     * 将指定id人查看其所有部门负责人 由上级层层上推
     *
     * @param $userId
     * @param bool $isArr
     * @return array|string
     *
     * create by dale 20180108
     */
    public function getChargeById($userId, $isArr = false)
    {
        $staff = XhhrmStaff::findFirst([
            'columns'    => 'iUserId,sDepIds',
            'conditions' => 'bDelete = 0 AND  iUserId = :iUserId:',
            'bind'       => ['iUserId' =>$userId]
        ]);
        $arr = [];
        $depIds = array_filter(explode(',', $staff->sDepIds));
        if (count($depIds) > 0) {
            foreach ($depIds as $depId) {
                $sql = "select iUserId from XHHrm_Staff  WHERE find_in_set('".$depId."',sChargeDeps) and bDelete = 0";
                $chargeId = $this->db->fetchOne($sql);
                if (isset($chargeId['iUserId'])) {  //没有直接走上级的上级
                    $arr[] = $chargeId['iUserId'];
                }
            }
            if ($arr[0] == $userId) {
                unset($arr[0]);
            }
            $arr = array_values($arr);
            if ($isArr) {
                return $arr;
            }
            return implode(',', $arr);
        }
    }


    /**
     * 获取应用分析数据 ajax
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     *
     * created by dale 20171118
     */
    public function getAppAction(){
        try {
            $schoolId = $this->request->getPost('schoolId') ;
            if(!$schoolId){
                return $this->sendErrorResponse(500,'缺少schoolId');
            }
            $state    = new StatsexamineController();
            $day      = $this->getFixDate($this->request->getPost('startDay'),$this->request->getPost('endDay'));
            $startDay = $day['startDay'];
            $endDay   = $day['endDay'];
            $state->initialize();
            $data     = $state->getStatsInfo($schoolId,strtotime($startDay),strtotime($endDay)+1);
//        $this->saveWeek(['iSchoolId'=>$schoolId,'mAppAnalyze'=>base64_encode(gzcompress(json_encode($data))),'iStartDay'=>strtotime($startDay),'iEndDay'=>strtotime($endDay)]);
            return json_encode($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage()
            );
        }

    }



    /**
     * 获取教师跟踪信息 根据学校
     *
     * @return string
     *
     * created by dale 20171115
     */
    public function getTchTrackAction()
    {
        try {
            $iSchoolId = $this->request->getPost('iSchoolId');


            if (!$iSchoolId) {
                return $this->sendErrorResponse('500','没有传入iSchoolId');
//                $iSchoolId=149;
            }

            $day   =  $this->getFixDate($this->request->getPost('startDay'),$this->request->getPost('endDay'));
            $startDay = $day['startDay'];
            $endDay   = $day['endDay'];
//            $startDay = date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y")));
//            $endDay = date("Y-m-d H:i:s", mktime(23, 59, 59, date("m"), date("d") - date("w") + 7, date("Y")));

            $sql = "select iUserId from XHSys_User WHERE iSchoolId={$iSchoolId} AND bDelete=0";
            $data = $this->db->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
            if(count($data)==0){
                return $this->sendJsonResponse([]);
            }
            $ids = implode(',', array_column($data, 'iUserId'));
            $sql = "select t.iTTchId,t.iUserId,t.tCreateDate,t.mContent,t.tTrackTime,IFNULL(t.mAppUse,'') as mAppUse,
                  IFNULL(t.mPurpose,'') as mPurpose,IFNULL(t.mResult,'') as mResult, u.sUserName
                  from XHTrack_Tch as t 
                  LEFT JOIN  XHSys_User as u ON  t.iUserId = u.iUserId where t.bDelete=0 AND t.iUserId in ({$ids})";
            $sql .= " AND t.tTrackTime >='{$startDay}' AND  t.tTrackTime <='{$endDay}' ";
            $sql = "select td.* from ({$sql}) as td ORDER BY td.iUserId";
            $data = $this->db->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
            $newData = [];
            foreach ($data as $index=>$row){
                $row['tTrackTime'] = date('Y-m-d',strtotime($row['tTrackTime']));
                $newData[$row['iUserId']][]=$row;
            }
            $newData = array_values($newData);
//            $this->saveWeek(['iSchoolId'=>$iSchoolId,'mTchTrack'=>base64_encode(gzcompress(json_encode($newData))),'iStartDay'=>strtotime($startDay),'iEndDay'=>strtotime($endDay)]);
            return $this->sendJsonResponse($newData);
        } catch (\Exception $e) {
            die($e->getMessage());
        }
    }

    /**
     * 获取跟踪数据
     *
     * created by dale 2017/11/15
     */
    public function getTaskTrackAction()
    {
        try{
            $iSchoolId = $this->request->getPost('iSchoolId');
            if (!$iSchoolId) {
                return $this->sendErrorResponse('500','没有传入iSchoolId');
            }
            $day   =  $this->getFixDate($this->request->getPost('startDay'),$this->request->getPost('endDay'));
            $startDay = $day['startDay'];
            $endDay   = $day['endDay'];
//            $startDay = date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y")));
//            $endDay = date("Y-m-d H:i:s", mktime(23, 59, 59, date("m"), date("d") - date("w") + 7, date("Y")));
            $builder = $this->modelsManager->createBuilder()
                ->columns('t.sTaskName,t.sOfferIds,t.tCreateDate,t.iTaskType,t.iState,sSchoolId')
                ->from(['t' => 'Admin\Models\track\XhtrackTask'])
                ->where('t.bDelete=0')
                ->andWhere('sSchoolId like :key:',['key'=>'%,'.$iSchoolId.',%'])
                ->andWhere('t.tCreateDate >=:startDay: AND t.tCreateDate <=:endDay:',['startDay'=>$startDay,'endDay'=>$endDay]);
            $data = $builder->getQuery()->execute()->toArray();
            $tc = new TrackController();
            $offerIds = []; //组合提问人姓名
            foreach ($data as $index=>$row){
                $data[$index]['taskType']=$tc->taskType[$row['iTaskType']];
                $data[$index]['state']=$tc->getStateName($row['iTaskType'],$row['iState']);
                $offerIds = array_merge($offerIds, explode(',', trim($row['sOfferIds'], ',')));
            }
            $offerIds = array_unique($offerIds);
            $userNameList = XhsysUser::getUserNameById($offerIds);
            foreach ($data as $index => &$row) {
                if ($row['sOfferIds']) {
                    $ids   = explode(',', trim($row['sOfferIds'], ','));
                    $names = [];
                    foreach ($ids as $userId) {
                        $names[] = $userNameList[$userId];
                    }
                    $data[$index]['sOfferUserName'] = implode(',', $names);
                }else{
                    $data[$index]['sOfferUserName'] ='';
                }
            }

//            $this->saveWeek(['iSchoolId'=>$iSchoolId,'mTaskTrack'=>base64_encode(gzcompress(json_encode($data))),'iStartDay'=>strtotime($startDay),'iEndDay'=>strtotime($endDay)]);
            return $this->sendJsonResponse($data);
        }catch (\Exception $e){
            die($e->getMessage());
        }

       
    }


    /**
     * ajax上传
     *
     * create by xjq 20180509
     */
    public function ajaxUploadAction(){
        $this->view->disable();
        if(!$this->request->hasFiles()){
            return $this->sendErrorResponse(400,'没有上传文件');
        };
        $file = $this->request->getUploadedFiles()[0];
        $filePath = Main::getConfigByName('appParse');
        $filePath = isset($filePath['tempPath']) ? $filePath['tempPath'] : '/Mailserver/cache/temp/';
        $fileName = $file->getName();
        $fullPath = $filePath . $fileName;
        if (!is_writable($filePath)) {
            return $this->sendJsonResponse(['state' =>  $filePath . '缓存无写入权限']);
        }
        $file->moveTo($fullPath);
        $url = Main::uploadToFileManageSystem($fullPath, 'img', null, true);
        @unlink($fullPath);

        return $this->sendJsonResponse(['url' => $url, 'fileName' => $fileName]);

    }

    /**
     * ajaxDelete删除
     * @param null $fileType
     * @return bool|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by xjq 20180509
     */
    public function ajaxDeleteAction($fileType=null)
    {
        $this->view->disable();
        $id = $this->request->getPost('id', 'string') or die('缺少参数id');
        $rmId = $this->request->getPost('rmId', 'int');
        if ($rmId == null) {
            die('缺少参数');
        }
        $obj = XhschoolWeekly::findFirst($id);
        $image = $obj->toArray();
        if($fileType == 'fileDelete'){
            $images = explode(',', $image['sFiles']);
            $url = '';
            foreach ($images as $key => $value) {
                if ($key != $rmId && $value != '') {
                    $url = $url . $value . ',';
                }
            }
            $obj->sFiles = $url;
        }else{
            $images = explode(',', $image['sImages']);
            $url = '';
            foreach ($images as $key => $value) {
                if ($key != $rmId && $value != '') {
                    $url = $url . $value . ',';
                }
            }
            $obj->sImages = $url;
        }
        $result = $obj->save();
        if ($result) {
            return $this->sendSuccessResponse('成功');
        }
        return false;
    }


    /**
     * 获取公开课信息 ajax
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 20171118
     */
    public function getClassAction()
    {
        $iSchoolId = $this->request->getPost('iSchoolId');
        if (!$iSchoolId) {
            return $this->sendErrorResponse('500','没有传入iSchoolId');
        }
        $day   =  $this->getFixDate($this->request->getPost('startDay'),$this->request->getPost('endDay'));

        $startDay = $day['startDay'];
        $endDay   = $day['endDay'];
//        $startDay = date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y")));
//        $endDay = date("Y-m-d H:i:s", mktime(23, 59, 59, date("m"), date("d") - date("w") + 7, date("Y")));

        try {
            $builder = $this->modelsManager->createBuilder()
                ->columns("p.iPCId,p.iUserId,p.tStartTime,p.iPCType,p.mContent,u.sUserName,up.sSelfPhone,
                               p.mAttendences,p.mDesc,p.mEvaluate,p.iEvalId,p.tEvalTime")
                ->from(['p' => 'Admin\Models\school\XhschoolPublicClass'])
                ->where('p.bDelete=0')->leftJoin('Admin\Models\user\XhsysUser', 'u.iUserId=p.iUserId', 'u')
                ->leftJoin('Admin\Models\user\XhsysUser', 'p.iEvalId=up.iUserId', 'up')->orderBy('p.tStartTime desc');

            $builder->andWhere('p.tStartTime>=:startTime: AND  p.tStartTime<=:endTime:', ['startTime' => $startDay, 'endTime' => $endDay]);

            $sql = "select iUserId from XHSys_User WHERE iSchoolId={$iSchoolId} AND bDelete=0";
            $data = $this->db->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
            if (count($data)==0) {
                return $this->sendJsonResponse([]);
            }
            $ids = array_values(array_column($data, 'iUserId'));

            $builder->andWhere('u.iUserId in ({ids:array})', ['ids' => $ids]);

            $data = $builder->getQuery()->execute()->toArray();
            Main::runUserNameById($data, ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId', 'iEvalId' => 'iEvalId'], true);
        } catch (\Exception $e) {
            die($e->getMessage());
        }
        $enums['iPCType'] = XhsysEnum::getEnumByNodeName('公开课类别');
        $newArray=[];
        foreach ($data as $index => $row) {
            $row['iPCType']      = $enums['iPCType'][$row['iPCType']];
            $row['tStartTime']   = date('Y-m-d H:i', strtotime($row['tStartTime']));
            $row['mAttendences'] = $row['mAttendences'] ?:'';
            $row['mEvaluate']    = $row['mEvaluate']    ?:'';
            $row['mDesc']        = $row['mDesc']        ?:'';
            $row['mContent']     = $row['mContent']     ?:'';
            $row['iEvalId']      = $row['iEvalId']      ?:'';
            $newArray[$row['iUserId']][]=$row;
        }
        $newArray = array_values($newArray);

//        $this->saveWeek(['iSchoolId'=>$iSchoolId,'mPClass'=>base64_encode(gzcompress(json_encode($newArray))),'iStartDay'=>strtotime($startDay),'iEndDay'=>strtotime($endDay)]);

        return $this->sendJsonResponse($newArray);
    }


//    public function getIdAction(){
//        $iSchoolId = $this->request->getPost('iSchoolId');
//        $day       = $this->getWeekAction();
//        $startDay  = $day['startDay'];
//        $endDay    = $day['endDay'];
//        $obj = XhschoolWeekly::findFirst([
//            'columns'    =>'iSWId',
//            'conditions' =>'iSchoolId = :iSchoolId: AND iStartDay=:iStartDay: AND iEndDay=:iEndDay:',
//            'bind'       =>['iSchoolId'=>$iSchoolId,'iStartDay'=>strtotime($startDay),'iEndDay'=>strtotime($endDay)],
//        ])->toArray();
//        return json_encode($obj);
//    }


//    private function saveWeek($arr){
//        $obj = XhschoolWeekly::findFirst([
//            'conditions'=>'iSchoolId = :iSchoolId: AND iStartDay=:iStartDay: AND iEndDay=:iEndDay:',
//            'bind'      =>['iSchoolId'=>$arr['iSchoolId'],'iStartDay'=>$arr['iStartDay'],'iEndDay'=>$arr['iEndDay']],
//        ]);
//        if(!$obj){
//            $obj = new XhschoolWeekly();
//        }
//        $obj->assign($arr);
//        $res = $obj->save();
//        return $res;
//    }


    /**
     * 保存周报信息  添加、编辑
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 20171118
     */
    public function saveWeekAction(){
        if(!UserPower::checkUserPower('School_List_Weekly_Add')){
             return $this->sendErrorResponse(500,'没有权限');
        }
        $iSWId = $this->request->getPost('iSWId');
        $day   =  $this->getFixDate($this->request->getPost('iStartDay'),$this->request->getPost('iEndDay'));
        if($iSWId){
            $obj = XhschoolWeekly::findFirst($iSWId);
        }else {
            $obj = XhschoolWeekly::findFirst([
                'conditions' => ' bDelete = 0 and iStartDay = :iStartDay: and iEndDay = :iEndDay: and iSchoolId = :iSchoolId: ',
                'bind'       => ['iStartDay' => strtotime($day['startDay']) ,'iEndDay' => strtotime($day['endDay']) , 'iSchoolId' => $this->request->getPost('iSchoolId')],
            ]);

            if(!$obj){
                $obj = new XhschoolWeekly();
            }
        }
        $data = $this->request->getPost();
        if(!$data['iSWId']){
            unset($data['iSWId']);
        }
        unset($data['sImages']);
        unset($data['sFiles']);
        $obj->assign($data);

        $obj->iStartDay = strtotime($day['startDay']);
        $obj->iEndDay   = strtotime($day['endDay']);
        if($this->request->getPost('mAppAnalyze')){
            $obj->mAppAnalyze = base64_encode(gzcompress($this->request->getPost('mAppAnalyze')));
        }
        if($this->request->getPost('mTaskTrack')){
            $obj->mTaskTrack  = base64_encode(gzcompress($this->request->getPost('mTaskTrack')));
        }
        if($this->request->getPost('mPClass')){
            $obj->mPClass     = base64_encode(gzcompress($this->request->getPost('mPClass')));
        }
        if($this->request->getPost('mTchTrack')){
            $obj->mTchTrack   = base64_encode(gzcompress($this->request->getPost('mTchTrack')));
        }
        if($this->request->getPost('sImages')){
            $obj->sImages .= $this->request->getPost('sImages');
        }
        if($this->request->getPost('sFiles')){
            $obj->sFiles .= $this->request->getPost('sFiles');
        }
        $res = $obj->save();
        if($res){
            if ($obj->iState == 1) {
                $schoolName = XhschoolInfo::findFirst([
                    'columns'    => 'sSchoolName',
                    'conditions' => 'bDelete= 0 and iSchoolId = :iSchoolId:',
                    'bind'       => ['iSchoolId' => $obj->iSchoolId]
                ])->sSchoolName;
//                Msg::insertWPageUserMsg(
//                    '周报',
//                    'school_weekly',
//                    $obj->iSWId,
//                    $schoolName . '周报'. date('Y-m-d', $obj->iStartDay) .'-'.
//                    date('Y-m-d', $obj->iEndDay),
//                    Tool::buildUrl('school_week/weeklyList',['iSWId' => $obj->iSWId]),
//                    [$this->getChargeById($obj->iCreateUserId , true)]
//                );
            } elseif (in_array($obj->iState, [2, 3])) { //处理
//                Msg::setMsg('school_weekly', [$obj->iSWId]);
            }
            return $this->sendSuccessResponse('保存成功');
        }else{
            return $this->sendErrorResponse(500,'保存失败');
        }
    }

    /**
     * 该学校周报列表
     *
     * @param $iSchoolId 学校编号
     * 
     * created by dale 20171118
     */
    public function weekListAction($iSchoolId){
        UserPower::checkUserPower('School_List_Weekly');
        $this->view->pick('school_week/weekList');
        Assets::importJs('js/school_week/weekList.js');
        if(!$iSchoolId){
            die('缺少参数iSchoolId');
        }
        $weeklys=XhschoolWeekly::find([
            'columns'    => 'iSWId,iStartDay,iEndDay,iState,iCreateUserId',
            'conditions' => 'iSchoolId = :iSchoolId: AND bDelete = 0',
            'bind'       => ['iSchoolId'=>$iSchoolId],
        ])->toArray();
        if(count($weeklys)==0){
            die('该学校没有周报记录');
        }else{
           foreach ($weeklys as $index=>$row){
               $weeklys[$index]['startDay']      = date('Y-m-d',$row['iStartDay']);
               $weeklys[$index]['endDay']        = date('Y-m-d',$row['iEndDay']);
               $weeklys[$index]['iState']        = $this->weekState[$row['iState']];
               unset($weeklys[$index]['iStartDay']);
               unset($weeklys[$index]['iEndDay']);
           }
            Main::runUserNameById($weeklys,['iCreateUserId'=>'iCreateUserId'],true);
        }
        $this->view->setVars([
            'weeklys' => $weeklys,
            'schoolName'=>XhschoolInfo::getSchoolArray()[$iSchoolId],
        ]);
    }

//    public function testAction(){
//        $str='[[{"iTTchId":"16","iUserId":"27048","tCreateDate":"2017-11-07 10:58:06","mContent":"kdiadn121\r\ndsaddas\r\ndddad","tTrackTime":"2017-11-07","mAppUse":"","mPurpose":"","mResult":"","sUserName":"\u5434\u83b9"},{"iTTchId":"18","iUserId":"27048","tCreateDate":"2017-11-07 20:24:27","mContent":"\u4e3a\u4ec0\u4e48\u4e0d\u8bf4\u81ea\u4fe1\u5462\uff1f\u4e0d\u81ea\u4fe1\u7684\u4eba\uff0c\u666e\u904d\u5185\u5fc3\u6bd4\u8f83\u8106\u5f31\u3002\u4e00\u4e2a\u81ea\u4fe1\u7684\u4eba\uff0c\u5bf9\u81ea\u5df1\u5145\u6ee1\u4fe1\u5fc3\uff0c\u505a\u4e8b\u5f80\u5f80\u5e26\u7740\u79ef\u6781\u5411\u4e0a\u7684\u529b\u91cf\uff0c\u5e76\u65f6\u523b\u5145\u6ee1\u6fc0\u60c5\u3002\u6240\u6709\u7684\u76f2\u76ee\u81ea\u4fe1\uff0c\u548c\u7a7a\u8179\u81ea\u4fe1\uff0c\u90fd\u662f\u81ea\u4ee5\u4e3a\u662f\u3002\u5fc3\u4e2d\u8981\u6709\u771f\u624d\u5b9e\u5b66\uff0c\u54ea\u6015\u5728\u4e0d\u65ad\u7684\u8bd5\u9519\uff0c\u4f46\u7ec8\u7a76\u80fd\u5230\u8fbe\u6500\u767b\u9ad8\u5cf0\u7684\u90a3\u4e00\u5929\u3002","tTrackTime":"2017-11-07","mAppUse":"\u591a\u6492\u6240\u591a\u591adsds","mPurpose":"dsd\u5b9a\u65f6\u8fbe","mResult":"\u591a\u6492\u591adsdsddss","sUserName":"\u5434\u83b9"}],[{"iTTchId":"17","iUserId":"27090","tCreateDate":"2017-11-07 16:04:20","mContent":"dasdsa","tTrackTime":"2017-11-07","mAppUse":"","mPurpose":"","mResult":"","sUserName":"\u6c88\u4e8e\u7acb"}]]';
//        var_dump(base64_encode(gzcompress($str)));
//
//        var_dump(gzuncompress(base64_decode(base64_encode(gzcompress($str)))));
//
//    }

    /**
     * 学校周报列表 esyui
     *
     * created by dale 20171120
     */
    public function weeklyListAction(){
        UserPower::checkUserPower('School_List_Weekly') or die('没有权限');
        Assets::easyUI();
        Assets::importJs('js/school_week/weeklyList.js');
        Assets::importJs('../ims/js/myTool.js');
        $this->view->pick('school_week/weeklyList');
        Template::exists('School_Weekly', 'list') or die(Main::showMessageModal('School_Weekly 配置文件不存在，请先创建！', 109106002));
        $listButton = $listSearchArr = [];
        if(UserPower::checkUserPower('School_List_Weekly_Grade')){
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_exmenu', 'text' => '考核打分', 'class' => 'bt_list_menu');
        }else{
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_exmenu', 'text' => '考核打分', 'class' => 'bt_list_menu','style' => 'display:none');
        }
        if (Power::exist('School_List_Weekly_EvalLevel')) {
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_levelMenu', 'text' => '周报评级', 'class' => 'bt_list_menu');
        }
//        $listButton[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        if(UserPower::checkUserPower('School_List_Weekly_Del')){
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        $schoolIds = UserPower::getAuthorizationSchool(true);
        if ($schoolIds === false) {
            return $this->sendViewError('无学校权限！');
        }
        elseif ($schoolIds === true) {
            $schoolIds = XhschoolInfo::getSchoolSupportArray();
        }
        $schoolIds[''] = '--请选择学校--';
        $states = $this->weekState;
        $states[''] = '--状态--';
        $dep = XhhrmDepart::findFirst([
            'columns'    => 'iDepId,sDepName',
            'conditions' => 'bDelete = 0 AND sTag = :sTag:',
            'bind'       => ['sTag'=>'XHYYB']
        ]);
        $area = XhhrmDepart::find([
            'columns'    => 'iDepId,sDepName,iParentId',
            'conditions' => 'bDelete = 0 AND iParentId = :iParentId:',
            'bind'       => ['iParentId'=>$dep->iDepId],
        ]);
        $area = array_column($area->toArray(),'sDepName','iDepId');
        $area[''] = '--请选择区--';
        $city[''] = '--请选择市--';
        $listSearchArr[] = array('type'=>'select', 'id'=>'list_search_area', 'data'=>$area,'default'=>'');
        $listSearchArr[] = array('type'=>'select', 'id'=>'list_search_city', 'data'=>$city,'default'=>'');
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_state', 'data' => $states, 'default' => '','style' => 'width:70px;' );
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        $this->view->setVars(array(
            'weekList' => Template::createList('weeklyList', 'School_Weekly', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButton),
            ]),
        ));
    }

    public function getDepsAction($pId){
        if($pId != ''){
            $data = XhhrmDepart::getDeps($pId);
            $arr[0] = [ 'id'=> '','text'=>'--请选择市--' ];
            foreach ($data as $index=>$value){
                $arr[] = ['id'=> $index,'text'=>$value];
            }
        }else{
            $arr[0] = [ 'id'=> '','text'=>'--请选择市--' ];
        }
        return $this->sendJsonResponse($arr);
    }




    /**
     * 获取周报数据表格数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 20171120
     */
    public function getDgAction(){
        try{
            $key      = $this->request->getPost('key','string');
            $schoolId = $this->request->getPost('schoolId','string');
            $state    = $this->request->getPost('state','string');
            $area     = $this->request->getPost('area','string');
            $city     = $this->request->getPost('city' ,'string');
            $order    = $this->request->getPost('order','string');
            $sort     = $this->request->getPost('sort','string');
            $iSWId    = $this->request->getPost('iSWId', 'string');
            $builder = $this->modelsManager->createBuilder()
                ->columns('w.iSWId,w.iSchoolId,w.iStartDay,w.iEndDay,w.iState,w.bDelete,w.iCreateUserId,u.sUserName,s.sSchoolName,w.iLastModifyUserId,w.iLevel,w.bLock')
                ->from(['w'=>'Admin\Models\school\XhschoolWeekly'])
                ->leftJoin('Admin\Models\school\XhschoolInfo','w.iSchoolId = s.iSchoolId','s')
                ->leftJoin('Admin\Models\user\XhsysUser','u.iUserId = w.iCreateUserId','u')
                ->where('w.bDelete = 0');

            $staff = false;
            if ($city || $area) {
                $depId = $city ?: $area;
                $staff = $this->db->fetchOne("select iUserId as userId from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$depId},%'");
            }
//            $schoolIds =  School::getPower(false , $staff ? $staff['userId'] : null);
            $schoolIds = School::getMergePower($staff ? $staff['userId'] : null, false);
            if ($schoolIds !== true) {
                if (count($schoolIds) <= 0) {
                    return $this->sendDataGridError('无学校权限！');
                }else {
                    $schoolIds = implode(',', $schoolIds);
                    $builder->andWhere("w.iSchoolId IN ({$schoolIds})");
                }
            }

            if($key){
                $builder->andWhere('u.sUserName like :key:  OR s.sSchoolName like :key: ',['key'=>'%'.$key.'%']);
            }
            if ( $state  || $state === "0") {
                 $builder->andWhere( ' w.iState = :state:' , [ 'state' => $state]);
            }
            if($schoolId){
                $builder->andWhere('w.iSchoolId = :iSchoolId:',['iSchoolId'=>$schoolId]);
            }
            if($order&&$sort){
                $builder->orderBy(" {$sort}   {$order} ");
            }else{
                $builder->orderBy(' iStartDay  desc');
            }
            if ($iSWId) {
                $builder->andWhere('iSWId = :iSWId:', ['iSWId' => $iSWId]);
            }

            $data = Main::runBuilderPage($builder);
            Main::runUserNameById($data['rows'] , ['iLastModifyUserId' => 'checkName'] , true);
            foreach ($data['rows'] as $index => $row){
                $data['rows'][$index]['iStartDay'] = date('Y-m-d',$row['iStartDay']);
                $data['rows'][$index]['iEndDay']   = date('Y-m-d',$row['iEndDay']);
                $data['rows'][$index]['iState']    = $this->weekState[$row['iState']];
                if($row['iLevel'] == 2){
                    $data['rows'][$index]['sSchoolName'] = '<font style="color:#FFCC33; " >'.$row['sSchoolName'].'</font>';
                }else if($row['iLevel'] == 3){
                    $data['rows'][$index]['sSchoolName'] = '<font style="color: darkmagenta">'.$row['sSchoolName'].'</font>';
                }
                if($row['iState'] != 2) {
                    $data['rows'][$index]['checkName'] = '';
                }
            }
            return $this->sendJsonResponse($data);
        }catch (\Exception $e){
            return $this->sendDataGridError(500,$e->getMessage(),false);
        }
    }


    /**
     * 删除周报
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 20171120
     */
    public function delWeeklyAction(){
        if(!UserPower::checkUserPower('School_List_Weekly_Del')){
            return $this->sendErrorResponse(500,'没有删除权限');
        }
        $ids = $this->request->getPost('ids');
        $ids = explode(',',$ids);
        $res = XhschoolWeekly::deleteRecord('iSWId',$ids);
        if($res){
            return $this->sendSuccessResponse('删除成功');
        }else{
            return $this->sendErrorResponse(500,'删除失败');
        }
    }

    /**
     * 应用使用数据统计
     *
     * created by dale 20171128
     */
    public function appCountAction(){
        $this->view->pick('school_week/appCount');
        Assets::importJs('js/school_week/appCount.js');
        Assets::select2();
        Assets::sweetAlert2();
        return $this->view->setVars([
            'viewAll'   => School::getPower() === true,
            'schoolArr' => User::getSchool(true),
//            'allowRefresh'  => UserPower::checkUserPower('Stats_Examine_Refresh')
        ]);
//        return true;
//        $schoolArr = UserPower::getAuthorizationSchool(true);
//        if ($schoolArr === false) {
//            return $this->sendViewError('无学校查看权限');
//        }
//        else if ($schoolArr === true) {
//            $schoolArr = XhschoolInfo::getSchoolSupportArray();
//        }
//        return $this->view->setVars([
//            'schoolArr' => $schoolArr
//        ]);

    }

    /**
     * 获取应用使用情况数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180124
     * modify by ck 20180516    使用缓存后删除
     */
    public function getAppDataAction(){
        $schoolId  = $this->request->getPost('schoolId');
        $startTime = $this->request->getPost('startTime');
        $endTime   = $this->request->getPost('endTime');
        if (!$schoolId) {
            return $this->sendErrorResponse(500, '缺少schoolId');
        }
        $startTime .= ' 00:00:00';
        $endTime   .= ' 23:59:59';
        $startTime  = strtotime($startTime);
        $endTime    = strtotime($endTime) + 1;
        $cacheKey   = "app_count_{$schoolId}_{$startTime}_{$endTime}";
        try {
            if (Cache::exists($cacheKey)) {
                $data = Cache::get($cacheKey);
                if (is_string($data)) {
                    Cache::delete($cacheKey);
                    return $this->sendErrorResponse(500, '获取应用缓存数据失败', $data);
                }
            }
            else {
                $state    = new StatsexamineController();
                $state->initialize();
//                $data     = $state->infoAction($schoolId, $startTime, $endTime);
                $data     = $state->getStatsInfo($schoolId, $startTime, $endTime);
            }
            Cache::delete($cacheKey);
            return $this->sendJsonResponse($data);
        }
        catch (\Exception $e){
            return $this->sendErrorResponse(500, '获取应用数据失败', $e->getMessage());
        }
    }

    /**
     * 开始缓存应用使用情况
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180124
     */
    public function startAppCountCacheAction()
    {
        set_time_limit(0);
        ignore_user_abort(true);
        $schoolId   = $this->request->getPost('schoolId', 'int');
        $startTime  = $this->request->getPost('startTime', 'string');
        $endTime    = $this->request->getPost('endTime', 'string');
        $startTime .= ' 00:00:00';
        $endTime   .= ' 23:59:59';
        $startTime  = strtotime($startTime);
        $endTime    = strtotime($endTime) + 1;
        if (!$schoolId || !$startTime || !$endTime) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        if ($startTime > time()) {
            return $this->sendErrorResponse(400, '日期超出限制，不可查询');
        }
//        if (($endTime - $startTime) > 3600 * 24 * 31){
//            return $this->sendErrorResponse(400, '最多查询一个月数据');
//        }
        $cacheKey = "app_count_{$schoolId}_{$startTime}_{$endTime}";
        if (Cache::exists($cacheKey)) {
            return $this->sendSuccessResponse('缓存已存在，可直接使用');
        }
        try {
            $state    = new StatsexamineController();
            $state->initialize();
//            $data     = $state->infoAction($schoolId,$startTime,$endTime);
            $data     = $state->getStatsInfo($schoolId,$startTime,$endTime);
            if (!Cache::save($cacheKey, $data, 3600 * 12)) {
                return $this->sendErrorResponse(500, '缓存保存失败');
            }
            return $this->sendSuccessResponse('缓存成功，可查询');
        }
        catch (\Exception $e) {
            Cache::save($cacheKey, '缓存失败：' . $e->getMessage(), 3600);
            return $this->sendErrorResponse(500, '获取应用数据失败', $e->getMessage(), true);
        }

    }

    /**
     * 检查应用使用情况缓存
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180124
     */
    public function checkAppCountCacheAction()
    {
        $schoolId   = $this->request->getPost('schoolId', 'int');
        $startTime  = $this->request->getPost('startTime', 'string');
        $endTime    = $this->request->getPost('endTime', 'string');
        $startTime .= ' 00:00:00';
        $endTime   .= ' 23:59:59';
        $startTime  = strtotime($startTime);
        $endTime    = strtotime($endTime) + 1;
        if (!$schoolId || !$startTime || !$endTime) {
            return $this->sendErrorResponse(400, '缺少必要参数', null, false);
        }
        $cacheKey = "app_count_{$schoolId}_{$startTime}_{$endTime}";
        if (!Cache::exists($cacheKey)) {
            return $this->sendErrorResponse(500, '缓存未生成', null, false);
        }
        return $this->sendSuccessResponse('缓存存在，可查询');
    }



    /**
     * 案例打分
     *
     * create by xjq 20180601
     */
    public function weekGradeAction(){
        $this->view->pick('school_week/weekGrade');
        Assets::select2();
        Assets::importJs('js/school_week/weekGrade.js');
        $this->view->setVar('schoolId' , $this->request->getQuery('schoolId'));
    }


    /**
     * 保存成绩
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180601
     */
    public function saveGradeAction(){
        $postData = $this->request->getPost();
        if (isset($postData['iRecId']) && $postData['iRecId']) {
            $obj = XhsysGrade::findFirst($postData['iRecId']);
        }else{
            $obj = XhsysGrade::findFirst([
                'conditions' => 'bDelete = 0  and iTargetId = :iTargetId:  and sMonth = :sMonth:  and iType = 2 ',
                'bind'       => [ 'iTargetId' => $postData['iTargetId'], 'sMonth' => $postData['sMonth']],
            ]);
            if (!$obj ) {
                $obj = new XhsysGrade();
            }else{
                return $this->sendErrorResponse(500 , '当月成绩已经生成请勿重复生成');
            }
        }
        $obj->assign($postData);
        $obj->iType = 2;//只限周报成绩
        if (!$obj->save()) {
            return $this->sendErrorResponse(500 , '保存失败');
        }
        return $this->sendSuccessResponse('保存成功');
    }

    /**
     * 成绩列表
     *
     * create by xjq 20180601
     */
    public function gradeListAction(){
        $this->view->pick('school_week/gradeList');
        $grades = XhsysGrade::find([
            'conditions' =>  'bDelete = 0 and iTargetId = :iTargetId: and iType = 2 ',
            'bind'       => ['iTargetId' => $this->request->getQuery('schoolId','int') ]
        ])->toArray();

        Main::runUserNameById($grades , ['iCreateUserId' => 'iCreateUserId'] , true );
        $this->view->setVar('grades' , $grades);
    }

    /**
     * 获取运营部区长及以上的人员id,以及名称
     *
     * create by xjq 20180615
     */
    public function getRunChargeIdFromAreaAction(){
        $depId = XhhrmDepart::findFirst([
            'columns' => 'iDepId',
            'conditions' => 'bDelete = 0 and sTag = :sTag:',
            'bind'       => ['sTag' => 'XHYYB']
        ])->toArray();
        $depId = $depId['iDepId'];
        $areaId = XhhrmDepart::find([
            'columns' => 'iDepId',
            'conditions' => 'bDelete = 0 and iParentId = :iParentId:',
            'bind'       => ['iParentId' => $depId],
        ])->toArray();

        $areaId = array_column($areaId , 'iDepId');
        $areaId[]= $depId;
        foreach ($areaId as $depId){
            $arr[] = " CONCAT(',',sChargeDeps,',') like '%,{$depId},%' ";
        }

        $sql = "select iUserId , sStaffName from XHHrm_Staff where bDelete = 0 AND (" . implode( ' OR ' , $arr ) . " ) " ;
        $users = $this->db->fetchAll($sql);
        return array_column($users , 'sStaffName','iUserId');
    }

    /**
     * 改变周报等级
     *
     * create by xjq 20180615
     */
    public function changeLevelAction(){
        try{
            $id    = $this->request->getPost('id' , 'int');
            $level = $this->request->getPost('level' , 'int');
            $week = XhschoolWeekly::findFirst($id);
            if (!$week) {
                return $this->sendErrorResponse(500 , '缺少参数');
            }
            $userId = Main::getLoginUserInfo('userId');
            if(!User::isAdmin() && !in_array($userId , array_keys($this->getRunChargeIdFromAreaAction())) && $week->bLock == 1 ){
                return $this->sendErrorResponse(500 ,'已经锁定，无法评级');
            }
            if(User::isAdmin() || in_array($userId , array_keys($this->getRunChargeIdFromAreaAction())) ){
                $week->bLock = 1;
            }
            $week->iLevel = $level;
            if (!$week->save()) {
                return $this->sendErrorResponse(500 , '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        }catch (\Exception $e){
            return $this->sendErrorResponse(500 , $e->getMessage());
        }

    }


}